const { now } = require('sequelize/lib/utils');
const { Room, User, Reservation, Order } = require('../models');

// 创建预订
const createReservation = async (req, res) => {
  try {
    const userId = req.user.id; // 从认证中间件获取用户ID
    const { room_id, date, start_time, end_time, duration, is_next_day, amount } = req.body;

    // 验证必要参数
    if (!room_id || !date || !start_time || !end_time || !duration || amount === undefined) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数',
        data: null
      });
    }

    // 验证房间是否存在
    const room = await Room.findOne({
      where: {
        id: room_id,
        status: 'available'
      }
    });

    if (!room) {
      return res.status(404).json({
        code: 404,
        message: '房间不存在或已被预订',
        data: null
      });
    }

    // 创建预订记录
    const reservationId = Date.now().toString(); // 使用时间戳作为ID
    const reservation = await Reservation.create({
      id: reservationId,
      user_id: userId,
      room_id,
      date,
      start_time,
      end_time,
      duration,
      is_next_day: is_next_day || false,
      amount,
      status: 'pending', // 待支付状态
      create_time: new Date()
    });

    // 同时创建一个订单记录
    const order = await Order.create({
      id: `ORD_${Date.now()}`,
      user_id: userId,
      order_type: 'reservation',
      reservation_id: reservationId,
      amount: reservation.amount,
      status: 'pending',
      order_no: `DD${Date.now()}`,
      create_time: new Date(),
      remark: `房间预订：日期${reservation.date}，时间${reservation.start_time}-${reservation.end_time}`
    });

    // 返回成功信息
    return res.status(200).json({
      code: 200,
      message: '预订创建成功',
      data: {
        order_id: reservationId
      }
    });
  } catch (error) {
    console.error('创建预订失败:', error);
    return res.status(500).json({
      code: 500,
      message: '创建预订失败，请稍后重试',
      data: null
    });
  }
};

// 获取用户预订列表
const getUserReservations = async (req, res) => {
  try {
    const userId = req.user.id;
    const status = req.query.status;
    const whereCondition = { user_id: userId };
    if (status) {
      whereCondition.status = status;
    }
    // 获取用户所有预订
    const reservations = await Reservation.findAll({
      where: whereCondition,
      order: [['create_time', 'DESC']]
    });
    reservations.map(reservation => {
       //如果预约结束时间小于等于当前时间，更新预约状态为'completed'
       const currentTime = new Date();
       const reservationEndTime = new Date(`${reservation.date}T${reservation.end_time}`);
       if (reservationEndTime <= currentTime && reservation.status == 'useing') {
        reservation.status = 'completed';
        reservation.save();
        console.log(`更新预约${reservation.id}状态为'completed'`);
       }
    })
    return res.status(200).json({
      code: 200,
      message: '获取预订列表成功',
      data: reservations
    });
  } catch (error) {
    console.error('获取预订列表失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取预订列表失败，请稍后重试',
      data: null
    });
  }
};

// 获取预订详情
const getReservationDetail = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;
    
    // 查找预订记录
    const reservation = await Reservation.findOne({
      where: { 
        id: id, 
        user_id: userId 
      }
    });
    
    if (!reservation) {
      return res.status(404).json({
        code: 404,
        message: '预订记录不存在',
        data: null
      });
    }
    
    // 查找关联的订单信息
    const order = await Order.findOne({
      where: { 
        reservation_id: id 
      }
    });
    
    // 合并订单信息到返回数据中
    const responseData = {
      ...reservation.toJSON(),
      orderNo: order ? order.order_no : '',
      order_id: order ? order.id : reservation.id
    };
    
    return res.status(200).json({
      code: 200,
      message: '获取预订详情成功',
      data: responseData
    });
  } catch (error) {
    console.error('获取预订详情失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取预订详情失败，请稍后重试',
      data: null
    });
  }
};

// 取消预订
const cancelReservation = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;
    
    // 查找预订记录
    const reservation = await Reservation.findOne({
      where: { 
        id: id, 
        user_id: userId 
      }
    });
    
    if (!reservation) {
      return res.status(404).json({
        code: 404,
        message: '预订记录不存在',
        data: null
      });
    }
    
    // 取消预订（修改状态）
    await reservation.update({
      status: 'canceled',
      update_time: new Date()
    });
    
    // 同时取消关联订单
    const order = await Order.findOne({
      where: { 
        reservation_id: id 
      }
    });
    
    if (order) {
      await order.update({
        status: 'canceled',
        update_time: new Date()
      });
    }
    
    return res.status(200).json({
      code: 200,
      message: '预订取消成功',
      data: null
    });
  } catch (error) {
    console.error('取消预订失败:', error);
    return res.status(500).json({
      code: 500,
      message: '取消预订失败，请稍后重试',
      data: null
    });
  }
};

/**
 * 获取房间预约时间段
 */
const getReservedTimes = async (req, res) => {
  try {
    console.log('[获取房间预约时间段] 请求参数:', req.params);
    const { id } = req.params;
   // 获取当前日期，将时间部分设置为 00:00:00
   const currentDate = new Date();
   currentDate.setHours(0, 0, 0, 0);
   const { Op } = require('sequelize');
    // 查找预订记录
    const reservations = await Reservation.findAll({
      where: { 
        room_id: id, 
        status: 'confirmed',
        date: {
          [Op.gte]: currentDate
        }
      }
    });
    console.log('[获取到的预约记录]', reservations);
    // 提取预订时间段
    const reservedTimes = reservations.map(reservation => {
      // 结合 date 和 start_time 创建完整的日期时间对象
      const startDateTimeStr = `${reservation.date} ${reservation.start_time}`;
      const startDate = new Date(startDateTimeStr);
    
      // 计算结束时间
      const endDate = new Date(startDate);
      endDate.setHours(endDate.getHours() + parseInt(reservation.duration));
    
      // 判断是否跨天
      let endDateStr = reservation.date;
      if (endDate.getDate() > startDate.getDate()) {
        const endDateObj = new Date(reservation.date);
        endDateObj.setDate(endDateObj.getDate() + 1);
        const year = endDateObj.getFullYear();
        const month = String(endDateObj.getMonth() + 1).padStart(2, '0');
        const day = String(endDateObj.getDate()).padStart(2, '0');
        endDateStr = `${year}-${month}-${day}`;
      }
    
      return {
        startDate: reservation.date,
        startHour: startDate.getHours(),
        endDate: endDateStr,
        endHour: endDate.getHours()
      };
    });
    console.log('[返回的数据]', reservedTimes);
     // 返回已预订时间段
    res.status(200).json({
      code: 200,
      message: '获取已预订时间段成功',
      data: reservedTimes
    });
  } catch (error) {
    console.error('获取已预订时间段时出错:', error);
    return res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      data: null
    });
  }
};
module.exports = {
  createReservation,
  getUserReservations,
  getReservationDetail,
  cancelReservation,
  getReservedTimes
}; 